package com.fitz.core.context;

import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author gousl01
 * @date 2021/3/15 14:37
 * @desc
 */
public class RequestContext extends ConcurrentHashMap<String,Object> {

    protected static Class<? extends RequestContext> contextClass = RequestContext.class;

    protected static final ThreadLocal<? extends RequestContext> threadLocal = new ThreadLocal<RequestContext>(){
        @Override
        protected RequestContext initialValue() {
            try {
                return contextClass.newInstance();
            } catch (Throwable e){
                throw new RuntimeException(e);
            }
        }
    };

    public static RequestContext getCurrentContext(){
        return threadLocal.get();
    }

    public HttpServletRequest getRequest(){
        return (HttpServletRequest) get(FilterConstants.REQUEST);
    }

    public void setRequest(HttpServletRequest request){
        put(FilterConstants.REQUEST, request);
    }

    public HttpServletResponse getResponse(){
        return (HttpServletResponse) get(FilterConstants.RESPONSE);
    }

    public void setResponse(HttpServletResponse response){
        put(FilterConstants.RESPONSE,response);
    }

    public Throwable getThrowable(){
        return (Throwable) get(FilterConstants.THROWABLE);
    }

    public void setThrowable(Throwable throwable){
        put(FilterConstants.THROWABLE, throwable);
    }

    public void set(String key,Object value){
        if (value != null){
            put(key,value);
            return;
        }
        remove(key);
    }

    public void unset() {
        threadLocal.remove();
    }

    public void setUrl(String url){
        put(FilterConstants.REQUEST_URL,url);
    }

    public String getUrl(){
        return (String) get(FilterConstants.REQUEST_URL);
    }

    public Map<String, List<String>> getRequestQueryParams() {
        return (Map<String, List<String>>) get(FilterConstants.REQUEST_QUERY_PARAMS);
    }

    public void setRequestQueryParams(Map<String, List<String>> qp) {
        put(FilterConstants.REQUEST_QUERY_PARAMS, qp);
    }

}
